import requests
import datetime
import controller.base
from util.misc import *
import json
import controller.text
import sys

from urllib3 import encode_multipart_formdata

# 微信小程序
APPID = 'wx43a3adfec9b1fa73'
SECRET = '31487f954b368c0c0708a2e220969973'

SCORE_TEXT = [
    ["非色素性", "色素性"],
    ["干性", "油性"],
    ["毛孔未扩张", "毛孔扩张"],
    ["耐受", "敏感"],
    ["细腻", "粗糙"]
]

TEXT = []
for n in range(16):
    t = getattr(controller.text, 'TEXT' + str(n+1))
    TEXT.append(t)

def getScoreText(type, score):
    if score > 50:
        return SCORE_TEXT[type][1]
    else:
        return SCORE_TEXT[type][0]


def getTips(scoresArray):
    p, o, f, s, t = scoresArray
    pType = p//50
    oType = o//50
    fType = f//50
    sType = s//50
    tType = t//50

    if o > 50:
        if (o - f) > 50:
            if (t - f) > 50:
                tType = fType
    test = (1-sType)<<2
    t1 = (1-oType)<<3
    t2 = (1-pType)<<1
    t3 = tType
    type = ((1-oType)<<3) + ((1-sType)<<2) + ((1-pType)<<1) + (1-tType)

    t = TEXT[type]

    return t['problem'], t['suggestion']

class SessionHandler(controller.base.BaseHandler):
    def post(self):
        code = self.get_body_para("code")
        rep = requests.get(
            'https://api.weixin.qq.com/sns/jscode2session?appid=' + APPID + '&secret=' + SECRET + '&js_code=' + code + '&grant_type=authorization_code')
        repJson = rep.json()

        # repJson = {
        #     'openid': "121211234234234",
        #     'session_key': "asdf"
        # }
        if 'errcode' in repJson.keys():
            if repJson['errcode'] == 40029:
                self.rsp(2, msg='无效code')
                return
            elif repJson['errcode'] == 40163:
                self.rsp(2, msg='code been used')
                return
            elif repJson['errcode'] == -1:
                self.rsp(2, msg='系统繁忙')
                return
            elif repJson['errcode'] == 45011:
                self.rsp(2, msg='频率限制，每个用户每分钟100次')
                return
            else:
                self.rsp(2, msg='未知错误')
                return

        else:
            openid = repJson['openid']
            session_key = repJson['session_key']
            token = random_str(64)
            expire = (datetime.datetime.now() + datetime.timedelta(days=3650)).strftime("%Y-%m-%d %H:%M:%S")
            sql = 'SELECT * FROM user WHERE wxid = %s'
            res = self.db.get(sql, openid)

            if res is None:
                sql = "INSERT INTO user (wxid, sessionKey, token,expire,createTime) VALUES (%s,%s,%s,%s,%s)"
                res1 = self.db.insert(sql, openid, session_key, token, expire,
                                      datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S"))
                user_id = res1
            else:
                sql = "UPDATE user SET token = %s, expire = %s WHERE id = %s"
                res1 = self.db.update(sql, token, expire, res["id"])
                user_id = res['id']

            data = {
                "user": {
                    "id": user_id,
                },
                "session": {
                    "token": token,
                    "expire": expire
                }
            }
            self.rsp(0, data)


class analysesHandler(controller.base.AuthHandler):
    def post(self):
        picUrl = self.get_body_para("picUrl")
        area = self.get_body_para("area")
        polar = self.get_body_para("polar")

        #requests
        payload = """------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data;
            name=\"area\"\n\n{}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; 
            name=\"purl\"\n\n{}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data;
            name=\"url\"\r\n\r\n {}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--""".format(area, picUrl[1], picUrl[0])

        try:
            r = requests.post(
                'http://223.223.186.117:5009/ai/classify',
                headers={'Content-Type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"},
                data=payload
            )
            rJson = r.json()
            logging.info(r)
            if rJson['code'] == 0:
                result = rJson['code']
                data = rJson['data']
                p = data['p_score']
                o = data['o_score']
                f = data['f_score']
                s = data['s_score']
                t = data['t_score']
            else:
                self.rsp(3, msg='Server Error')
                return

        except Exception:
            self.rsp(3, msg='Server Error')
            return

        createTime = datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S")
        sql = "INSERT INTO analysis (photoUrl,area, polar,createTime,result, userId, pigmentation, oil, follicular, sensitivity, texture) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
        res = self.db.insert(sql, json.dumps(picUrl), area, polar, createTime, result, self.user["id"], p, o, f, s, t)

        scoresArray = [p, o, f, s, t]
        scores = []

        for i in range(0, 5):
            score = {
                "score": scoresArray[i],
                "text": getScoreText(i, scoresArray[i])
            }
            scores.append(score)

        problem, suggestion = getTips(scoresArray)
        data = {
            "id": res,
            "picUrl": picUrl,
            "area": area,
            "polar": polar,
            "createTime": createTime,
            "result": scores,
            "problem": problem,
            "suggestion": suggestion
        }
        self.rsp(0, data)

    def get(self):
        page = self.get_query_argument('page', default=None)
        if page is not None:
            page = int(page)
        if (page is not None) and page <= 0:
            self.rsp(6, msg="page starts from 1")
            return
        sql = 'SELECT * FROM analysis WHERE userId = %s order by id desc'
        res = self.db.query(sql, self.user["id"])
        if res is None:
            self.rsp(0, msg="no analysis")
            return
        length = len(res)

        start = 0
        end = length
        hasMore = False
        if page is not None:
            start = 20 * (page - 1)
            end = 20 * page
            if start > (length - 1):
                self.rsp(0, msg="no analysis")
                return
            if end >= length:
                end = length
            else:
                hasMore = True

        data = []
        for idx in range(start, end):
            ana = res[idx]
            anaId = ana['id']
            picUrl = json.loads(ana['photoUrl'])
            area = ana['area']
            polar = ana['polar']
            createTime = ana["createTime"].strftime("%Y/%m/%d")
            p = ana['pigmentation']
            o = ana['oil']
            f = ana['follicular']
            s = ana['sensitivity']
            t = ana['texture']
            scoresArray = [p, o, f, s, t]
            scores = []

            for i in range(0, 5):
                score = {
                    "score": scoresArray[i],
                    "text": getScoreText(i, scoresArray[i])
                }
                scores.append(score)

            problem, suggestion = getTips(scoresArray)
            analysis = {
                "id": anaId,
                "picUrl": picUrl,
                "area": area,
                "polar": polar,
                "createTime": createTime,
                "result": scores,
                "problem": problem,
                "suggestion": suggestion
            }
            data.append(analysis)
        self.rsp(0, data)




class analysisHandler(controller.base.AuthHandler):
    def get(self, analysis_id):
        print(analysis_id)
        pass

